const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  if (req.url === '/api/menuList') {
    const users = {
        success:"true",
        data:{
          '/guide/': [
            {
              title: '请求接口-平台文档',
              collapsable: false,
              children: [
                '',
                'using-vue',
              ]
            },
            {
              title: '请求接口-基础文档',
              collapsable: false,
              children: [
                'test',
                "test0",
                'test1',
                'test2',
              ]
            },
            {
              title: '请求接口-Group 3',
              collapsable: false,
              children: [
                {
                  title: '代码相关文档',
                  collapsable: false,
                  path: "/guide/subgroup1/",
                  children: [
                    'subgroup1/test3',
                    'subgroup1/test4'
                  ]
                },
                {
                  title: '视图相关文档',
                  collapsable: false,
                  path: "/guide/subgroup2/",
                  children: [
                    'subgroup2/test5',
                    'subgroup2/test6'
                  ]
                }
              ]
            }
          ],
          sidebarDepth: -1  // 设置为 -1，确保所有标题都能展开
        },
        url:req.url,
        code:0,
        msg:"请求成功！"
    }
    res.setHeader('Content-Type', 'application/json');
    
    // 设置允许的请求来源  配置的时候不能加 / 
    res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8081',"http://localhost:8081");
    res.end(JSON.stringify(users));
  }
  // 获取.md详情
  else if(req.url === "/api/mdDetails") {
    // 处理其它请求，例如获取 .md 文件
    const filePath = path.join(__dirname, "test.md");
    // const extname = path.extname(filePath);
    console.log("filePath",filePath);
    // 仅处理 .md 文件请求
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        res.statusCode = 404;
        res.end('Not Found');
      } else {
        res.setHeader('Content-Type', 'text/plain');
        res.end(data);
      }
    });
  }
  else {
    res.statusCode = 404;
    res.end();
  }
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});